import { App, Component } from 'vue'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { ErrorPageRoute, LoginRoute, RedirectRoute } from '@/router/base'
import { ErrorPage, Layout } from '@/router/constant'
import { UserMenu } from '@/api/common/types'
import { useUserStore } from '@/store/modules/user'

export const constantRouter: RouteRecordRaw[] = [LoginRoute, RedirectRoute, ErrorPageRoute]

export const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRouter,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

export async function setupRouter(app: App) {
  app.use(router)
  // 创建路由守卫
  // createRouterGuards(router)
}

const modules = import.meta.glob('@/views/**/index.vue', { eager: true, import: 'default' })

export const menuToRouter = async (menus?: UserMenu[], isChildren = false): Promise<RouteRecordRaw[] | undefined> => {
  if (!menus || !menus.length) {
    return undefined
  }
  const sss = menus.map(async (menu) => {
    const { name, icon, path, component, children, hidden, keepAlive, ...meta } = menu

    const compPath = `/src/views/${component?.replace('sys/', 'system/')}/index.vue`
    const comp = modules[compPath]
    const pageComp = (component === 'Layout' ? Layout : comp ? comp : ErrorPage) as Component
    let pageName = comp ? pageComp.name : path.replace('/', '')

    let tempPath = isChildren ? path : '/' + path
    let link: string = ''
    if (meta?.target) {
      //uri编码
      tempPath = encodeURIComponent(tempPath)
      pageName && (pageName = encodeURIComponent(pageName))
      link = tempPath
      // console.log(`[${pageName}]: `, tempPath)
    }

    const router: RouteRecordRaw = {
      path: tempPath,
      component: pageComp,
      name: pageName,
      meta: {
        ...meta,
        hideMenu: !!hidden,
        title: name,
        icon,
        link
      },
      children: await menuToRouter(children, true)
    }
    // meta?.target && console.log('router: ', router)
    // router.name === 'test' && console.log(`router[${router.name.toString()}]: `, router)
    // router.name === 'test' && console.log(`menu[${router.name.toString()}]: `, menu)
    if (!!keepAlive && pageName) {
      useUserStore().addCacheMenu(pageName)
    }

    return router
  })
  return await Promise.all(sss)
}
